package shaw.wifi.encryption;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;


public class AesEncryption {
	private Cipher aesCipher;
	private SecretKeySpec skSpec;
	private IvParameterSpec ivSpec;
	
	private boolean isSet = false;
	
	static {
		Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
	}
	
	public AesEncryption() {
		initAes();
	}
	
	public void initAes() {
		if(aesCipher == null) {
			try {
				aesCipher = Cipher.getInstance("AES/CBC/PKCS5PADDING", "BC");
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			} catch (NoSuchPaddingException e) {
				e.printStackTrace();
			} catch (NoSuchProviderException e) {
				e.printStackTrace();
			}
		}
	}
	
	public void setSharedSecret(byte[] secret) {
		skSpec = new SecretKeySpec(secret, "AES");
		System.out.println("got secret: ");
		for(int i = 0; i<secret.length; i++) {
			System.out.print(secret[i] + " ");
		}
		System.out.print("\n");
	}
	
	public void setIvParameterSpec(byte[] iv) {
		ivSpec = new IvParameterSpec(iv);
	
		isSet = true;
	}
	
	public byte[] encryptAes(byte[] plain) {
		byte[] crypt = null;
		
		try {
			aesCipher.init(Cipher.ENCRYPT_MODE, skSpec, ivSpec);
			crypt = aesCipher.doFinal(plain);
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		} catch (InvalidAlgorithmParameterException e) {
			e.printStackTrace();
		}
		
		return crypt;
	}
	
	public byte[] decryptAes(byte[] crypt) {
		byte[] plain = null;
		
		try {
			aesCipher.init(Cipher.DECRYPT_MODE, skSpec, ivSpec);
			plain = aesCipher.doFinal(crypt);
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		} catch (InvalidAlgorithmParameterException e) {
			e.printStackTrace();
		}
		
		return plain;
	}

	public boolean isSetup() {
		return isSet;
	}
}
